#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author  : hu_cl
# @Contact : 760730895@qq.com 
# @Date    : 2020/10/12 16:36
# @File    : pgsql_backups.py
import paramiko
import os
import time


class BackupPgsql(object):
    def __init__(self, host, port, username, password, paths, db_name):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.paths = paths
        self.file_name = "pgsql_backup_{}_{}.sql".format(db_name, time.strftime("%Y%m%d"))
        self.ssh_client = paramiko.SSHClient()
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh_client.connect(hostname=host, username=username, password=password, port=port)

    def pgsql_backup_cmd(self, bk_ssh_client, db_name, db_username, db_password):
        # 远程备份数据库
        command = "pg_dump -U {} {}>{}/{}"\
            .format(db_username, db_name, self.paths, self.file_name)  # 备份命令
        # pg_dump -U postgresql -d yc_data_visual > /tmp/dump.sql
        # pg_dump -U postgres TestDb1>TestDb14.sql
        stdin, stdout, stderr = bk_ssh_client.exec_command(command)
        res, err = stdout.read(), stderr.read()
        if err:
            print('执行back up %s文件有信息返回为%s' % (self.file_name, err.decode()))
        else:
            print('backup %s文件成功' % self.file_name)

    def pgsql_zip_files(self, zip_ssh_client):
        # 压缩服务器上的目标文件
        zip_commands = ('cd {}'.format(self.paths), 'zip -r {}.zip {}'.format(self.file_name, self.file_name))
        # cd /tmp, zip -r mysql_backup20200727.sql.zip mysql_backup20200727.sql
        zip_stdin, zip_stdout, zip_stderr = zip_ssh_client.exec_command(' \n '.join(zip_commands))
        res, err = zip_stdout.read(), zip_stderr.read()
        if err:
            print('执行压缩%s文件有信息返回为%s' % (self.file_name, err.decode()))
        else:
            print('压缩%s文件成功' % self.file_name)

    def pgsql_download(self, dl_ssh_client, dl_local):
        ftp_client = dl_ssh_client.open_sftp()
        print('正在下载%s.zip，请等待' % self.file_name)
        if not os.path.exists(dl_local):
            os.makedirs(dl_local)
        try:
            ftp_client.get('{}/{}.zip'.format(self.paths, self.file_name), r'{}/{}.zip'.format(dl_local, self.file_name))
        except Exception as exp:
            print('下载mysql备份数据失败 %s' % exp)
        else:
            print("pgsql备份数据下载完成")
        ftp_client.close()

    def pgsql_remove_file(self, rm_ssh_client):
        # 删除服务器上 生成的压缩文件
        commands = ('cd {}'.format(self.paths),
                    'rm -f {}/{}'.format(self.paths, self.file_name),
                    'rm -f {}/{}.zip'.format(self.paths, self.file_name))
        rm_stdin, rm_stdout, rm_stderr = rm_ssh_client.exec_command(' \n '.join(commands))
        res, err = rm_stdout.read(), rm_stderr.read()
        if err:
            print('删除文件失败,错误信息为%s' % err.decode())
        else:
            print('删除压缩文件成功')